/* ringbuffer handler */

/* Copyright (C) 2009 David Zanetti
 *
 *  This program is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; version 2 of the License.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License along
 *  with this program; if not, write to the Free Software Foundation, Inc.,
 *  51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */


#include <stdio.h>
#include <avr/interrupt.h>
#include "ringbuffer.h"

/* write to the given ring buffer, if we can */
uint8_t ring_write(char *buf, uint8_t *wp, uint8_t mask, char value) {
	uint8_t ret;
	cli();
	ret = ring_write_unsafe(buf, wp, mask, value);
	sei();
	return ret;
}

uint8_t ring_write_unsafe(char *buf, uint8_t *wp, uint8_t mask, char value) {
	*wp = (*wp + 1) & mask;
	*(buf + *wp) = value;
	return 1;
}

/* unconditional write */
uint8_t ring_write_force(char *buf, uint8_t *rp, uint8_t *wp, uint8_t mask,
		char value) {
	uint8_t ret;
	cli();
	ret = ring_write_force_unsafe(buf, rp, wp, mask, value);
	sei();
	return ret;
}

uint8_t ring_write_force_unsafe(char *buf, uint8_t *rp, uint8_t *wp, 
		uint8_t mask, char value) {
	/* advance the writer pointer */
	*wp = (*wp + 1) & mask;

	/* if they are the same, then consume a read character as overrun */
	if (*wp == *rp) {
		*rp = (*rp + 1) & mask;
	}

	*(buf+ *wp) = value;
	return 1;
}

uint8_t ring_writeable(uint8_t rp, uint8_t wp, uint8_t mask) {
	uint8_t ret;
	cli();
	ret = ring_writeable_unsafe(rp, wp, mask);
	sei();
	return ret;
}

uint8_t ring_writeable_unsafe(uint8_t rp, uint8_t wp, uint8_t mask) {
	if (((wp + 1) & mask) == rp) {
		return 0;
	}
	return 1;
}

char ring_read(char *buf, uint8_t *rp, uint8_t mask) {
	char ret;
	cli();
	ret = ring_read_unsafe(buf, rp, mask);
	sei();
	return ret;
}

char ring_read_unsafe(char *buf, uint8_t *rp, uint8_t mask) {
	*rp = (*rp + 1) & mask;
	return *(buf + *rp);
}

uint8_t ring_readable(uint8_t rp, const uint8_t wp, uint8_t mask) {
	uint8_t ret;
	cli();
	ret = ring_readable_unsafe(rp, wp, mask);
	sei();
	return ret;
}

uint8_t ring_readable_unsafe(uint8_t rp, const uint8_t wp, uint8_t mask) {
	if (rp != wp) {
		return 1;
	}
	return 0;
}

